﻿using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace CWM.Skinn
{
    public static partial class SkinnContextCommands
    {
        [CtxMenuItem("Renderer/Export/TextFilter/Blendshapes", 
            "Exports a text file with blend-shape names.", 0)]
        public static void RendererExportTextFilter()
        {
            string path = EditorUtility.SaveFilePanelInProject("Export TextFilter", "", "txt", "TextFilter");
            if (path == "") return;
            if (!path.EndsWith(".txt")) Debug.LogWarning("file path should end with .txt");

            var meshes = new List<Mesh>();
            foreach (var item in SkinnContext.GetContextItems())
            {
                var context = item.GetComponent<Renderer>();
                if (SkinnEx.IsNullOrNotInAScene(context)) continue;

                var mesh = context.GetSharedMesh();
                if (mesh) meshes.Add(mesh);
            }

            if (System.IO.File.Exists(path)) AssetDatabase.DeleteAsset(path);
            var blendshapes = meshes.ToArray().GetBlendshapeNames().ToArray();
            if (!path.EndsWith(".txt")) Debug.LogWarning("file path should end with .txt");
            if (System.IO.File.Exists(path)) AssetDatabase.DeleteAsset(path);
            ShapeFilter.Write(path, null, ShapeFilter.GetDefaultFunctions, blendshapes);
            AssetDatabase.Refresh();
        }
    }
}